package com.jackrain.nea.wms.mq;

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.wms.mapper.WmsSqlMapper;
import com.jackrain.nea.wms.utils.ObjectToUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.sql.Timestamp;

/**
 * Created by Lucky dog on 2017/5/22.
 * 记录日志
 */
@Aspect
@Component
@Slf4j
public class MQAspect {

    @Autowired
    private WmsSqlMapper sqlMapper;

    @Before(value = "execution(* com.jackrain.nea.wms.mq.SendMqService.send(..))&& args(message,valueHolder)", argNames = "point,message,valueHolder")
    public void beforeSend(JoinPoint point, Message message, ValueHolder valueHolder) {

        try {
            JSONObject insertKeys = new JSONObject();
            insertKeys.put("ID", Tools.getSequence("ons_sendmonitor"));
            insertKeys.put("AD_CLIENT_ID", 37);
            insertKeys.put("OWNERID", 893);
            insertKeys.put("MODIFIERID", 893);
            insertKeys.put("CREATIONDATE", new Timestamp(System.currentTimeMillis()));
            insertKeys.put("MODIFIEDDATE", new Timestamp(System.currentTimeMillis()));
            insertKeys.put("ISACTIVE", "Y");
            insertKeys.put("PTYPE", "1");//云端数据
            insertKeys.put("TOPIC", message.getTopic());
            insertKeys.put("TAG", message.getTag());
            insertKeys.put("MSGKEY", message.getKey());
            insertKeys.put("STATE", "1");//0:待发送,1:待消费,2:消费成功 默认待消费
            insertKeys.put("CONSUMER_ERROR", "N");//消费是否存在异常
            insertKeys.put("PDESC", ObjectToUtil.getString(valueHolder.get("pdesc"), ""));
            sqlMapper.insert("ons_sendmonitor", insertKeys);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            recCloudErrorLog("发送消息前", sw.toString(), message);
        }

        log.debug("beforeSend");

    }

    @AfterReturning(value = "execution(* com.jackrain.nea.wms.mq.SendMqService.send(..))&& args(message,valueHolder)", returning = "result", argNames = "point,result,message,valueHolder")
    public void afterSend(JoinPoint point, SendResult result, Message message, ValueHolder valueHolder) {

        log.debug("afterSend");

        //回写消息状态
        JSONObject setKeys = new JSONObject();
        setKeys.put("MSGID", message.getMsgID());
        JSONObject whereKeys = new JSONObject();
        whereKeys.put("MSGKEY", message.getKey());
        sqlMapper.update("ons_sendmonitor", setKeys, whereKeys);

    }

    @AfterThrowing(value = "execution(* com.jackrain.nea.wms.mq.SendMqService.send(..))&& args(message,valueHolder)", throwing = "e", argNames = "joinPoint,e,message,valueHolder")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e, Message message, ValueHolder valueHolder) throws Exception {

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String error = sw.toString();
        //回写消息状态
        JSONObject setKeys = new JSONObject();
        setKeys.put("STATE", "0");//0:待发送,1:待消费,2:消费成功 默认待消费
        setKeys.put("MSGID", message.getMsgID());
        JSONObject whereKeys = new JSONObject();
        whereKeys.put("MSGKEY", message.getKey());
        sqlMapper.update("ons_sendmonitor", setKeys, whereKeys);
        //记录错误日志
        recCloudErrorLog("发送消息报错", error, message);

    }

    /**
     * 记录日志
     *
     * @param name    错误标题
     * @param error   详细错误信息
     * @param message
     */
    private void recCloudErrorLog(String name, String error, Message message) {

        try {
            //记录日志
            JSONObject insertKeys = new JSONObject();
            insertKeys.put("ID", Tools.getSequence("oms_clouderror"));
            insertKeys.put("AD_CLIENT_ID", 37);
            insertKeys.put("OWNERID", 893);
            insertKeys.put("MODIFIERID", 893);
            insertKeys.put("CREATIONDATE", new Timestamp(System.currentTimeMillis()));
            insertKeys.put("MODIFIEDDATE", new Timestamp(System.currentTimeMillis()));
            insertKeys.put("ISACTIVE", "Y");
            insertKeys.put("NAME", name);
            insertKeys.put("PTYPE", "1");//服务器端
            insertKeys.put("ERRORINFO", error);
            insertKeys.put("IP", NetUtils.getLocalAddress().getHostAddress());
            insertKeys.put("ORIGMSGKEY", message.getKey());
            insertKeys.put("TOPIC", message.getTopic());
            insertKeys.put("TAG", message.getTag());
            Serializable ser = MsgConvertUtil.objectDeserialize(message.getBody());
            if (ser instanceof JSONArray) {
                JSONArray paramArray = JSONArray.parseArray(ser.toString());
                insertKeys.put("DUTEINFO", paramArray.toJSONString());
            } else if (ser instanceof JSONObject) {
                JSONObject parapObject = JSONObject.parseObject(ser.toString());
                insertKeys.put("DUTEINFO", parapObject.toJSONString());
            }
            sqlMapper.insert("oms_clouderror", insertKeys);

        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

}
